package com.github.base.service.impl;

import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.base.domain.User;
import com.github.base.exception.CommonException;
import com.github.base.global.Const;
import com.github.base.mapper.UserMapper;
import com.github.base.service.AuthService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * @program: base
 * @description: 认证
 * @author: hui.zhang
 * @date: 2021/1/29 10:03 上午
 **/

@Slf4j
@Service
@AllArgsConstructor
@SuppressWarnings("all")
public class AuthServiceImpl implements AuthService {
    private final UserMapper userMapper;


    @Override
    public SaTokenInfo login(String username, String password) {
        LambdaQueryWrapper<User> wrapper = Wrappers.<User>query().lambda().select();
        wrapper.eq(User::getUsername, username);
        wrapper.eq(User::getState, Const.YES);
        wrapper.eq(User::getUsable, Const.YES);
        User user = userMapper.selectOne(wrapper);
        if (ObjectUtil.isEmpty(user)) {
            throw new CommonException("账号或密码错误");
        } else {
            if (StrUtil.equals(password, user.getPassword())) {
                StpUtil.login(user.getId());
                SaTokenInfo tokenInfo = StpUtil.getTokenInfo();
                return tokenInfo;
            } else {
                throw new CommonException("账号或密码错误");
            }
        }
    }
}
